﻿using CommonLibrary;
using CommonLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CommonSite.Common
{
    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return UserAction.GetCurrentUser() != null;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("/Account/Login?ret=" + filterContext.RequestContext.HttpContext.Request.RawUrl);
        }
    }

    public class AdminAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var user = UserAction.GetCurrentUser();
            if (user == null)
                return false;

            if (user.IsSupperAdmin == true)
                return true;

            using (CommonDatabase db = new CommonDatabase())
            {
                if (db.sys_UserRole.Where(k => k.UserId == user.UserId &&
                                               (k.RoleId == 1 || k.RoleId == 2))
                      .Count() > 0) 
                {
                    return true;
                }
            }

            return false;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("/Account/Login?ret=" +
                Uri.EscapeUriString(filterContext.RequestContext.HttpContext.Request.Path));
        }
    }
}